// events-manager.js
class EventsManager {
    constructor() {
        this.events = {
            all: [],      // 全部事件
            move: [],     // 移动事件  
            detection: [], // 检测事件
            error: []     // 错误事件
        };
        this.init();
    }

    init() {
        // 初始化显示
        this.renderAllEvents();
    }

    // 添加新事件
    addEvent(type, message, data = null, previewData = null) {
        const event = {
            id: Date.now() + Math.random().toString(36).substr(2, 9),
            timestamp: new Date().toLocaleString('zh-CN'),
            type: type,
            message: message,
            data: data,
            previewData: previewData || data // 如果没有预览数据，使用完整数据
        };

        // 添加到对应分类
        this.events.all.unshift(event); // 最新的在前面
        this.events[type].unshift(event);

        // 限制事件数量（可选）
        this.limitEventsSize();

        // 更新显示
        this.renderEvents(type);
        this.renderAllEvents();


        // 触发自定义事件（可选）
        this.emitEventAdded(event);
    }

    // 渲染所有事件
    renderAllEvents() {
        this.renderEvents('all');
        this.renderEvents('move');
        this.renderEvents('detection');
        this.renderEvents('error');
    }

    // 渲染特定类型事件
    renderEvents(type) {
        const container = document.getElementById(`events-container-${type}`);
        if (!container) return;

        const events = this.events[type];
        container.innerHTML = '';

        if (events.length === 0) {
            container.innerHTML = '<div class="no-events">暂无事件记录</div>';
            return;
        }

        events.forEach(event => {
            const eventElement = this.createEventElement(event);
            container.appendChild(eventElement);
        });
    }

    // 创建事件元素
    createEventElement(event) {
        const eventDiv = document.createElement('div');
        eventDiv.className = `event-item event-${event.type}`;
        eventDiv.setAttribute('data-event-id', event.id);

        // 使用预览数据或完整数据的前100个字符作为预览
        const displayData = event.previewData || event.data;
        const previewText = this.formatPreviewData(displayData);

        eventDiv.innerHTML = `
            <div class="event-header">
                <div class="event-message-container">
                    <div class="event-message">${event.message}&nbsp;&nbsp;&nbsp;🕒${event.timestamp}</div>
                </div>
                <span class="event-type ${event.type}">${this.getTypeText(event.type)}</span>
            </div>
            ${displayData ? `
                <div class="event-data">
                    <div class="data-preview">${previewText}</div>
                </div>
            ` : ''}
        `;

        // 添加双击事件
        eventDiv.addEventListener('dblclick', (e) => {
            e.stopPropagation();
            this.showEventDetail(event);
        });

        // 添加悬浮事件显示完整预览
        const eventData = eventDiv.querySelector('.event-data');
        if (eventData) {
            eventData.addEventListener('mouseenter', (e) => {
                this.showDataTooltip(event, e.target);
            });
            
            eventData.addEventListener('mouseleave', (e) => {
                this.hideDataTooltip();
            });
        }

        return eventDiv;
    }

    // 格式化预览数据
    formatPreviewData(data) {
        if (!data) return '';
        
        if (typeof data === 'object') {
            const jsonStr = JSON.stringify(data);
            return this.truncateText(jsonStr);
        }
        
        return this.truncateText(String(data));
    }

    // 截断文本
    truncateText(text, maxLength) {
        if (text.length <= maxLength) return text;
        return text.substring(0, maxLength) + '...';
    }

    // 显示数据提示框
    showDataTooltip(event, target) {
        this.hideDataTooltip();
        
        const tooltip = document.createElement('div');
        tooltip.className = 'data-tooltip';
        tooltip.innerHTML = `
            <div class="tooltip-content">
                <div class="tooltip-header">
                    <span class="tooltip-title">数据预览</span>
                    <button class="tooltip-expand" onclick="eventsManager.showEventDetail(${JSON.stringify(event).replace(/"/g, '&quot;')})">完整查看</button>
                </div>
                <pre class="tooltip-data">${this.formatEventData(event.previewData || event.data)}</pre>
            </div>
        `;

        document.body.appendChild(tooltip);

        // 定位提示框
        const rect = target.getBoundingClientRect();
        tooltip.style.left = rect.left + 'px';
        tooltip.style.top = (rect.bottom + 5) + 'px';
        
        this.currentTooltip = tooltip;
    }

    // 隐藏数据提示框
    hideDataTooltip() {
        if (this.currentTooltip) {
            this.currentTooltip.remove();
            this.currentTooltip = null;
        }
    }

    // 获取类型文本
    getTypeText(type) {
        const typeMap = {
            'move': '移动',
            'detection': '检测',
            'error': '错误',
            'all': '全部'
        };
        return typeMap[type] || type;
    }

    // 格式化事件数据
    formatEventData(data) {
        if (!data) return '无数据';
        
        if (typeof data === 'object') {
            return JSON.stringify(data, null, 2);
        }
        return String(data);
    }

    // 清除事件
    clearEvents(type = 'all') {
        if (type === 'all') {
            // 清除所有事件
            this.events = { all: [], move: [], detection: [], error: [] };
        } else {
            // 清除特定类型事件
            this.events[type] = [];
            // 从all中移除该类型事件
            this.events.all = this.events.all.filter(event => event.type !== type);
        }

        this.renderAllEvents();
        this.renderEvents(type);
    }

    // 导出事件
    exportEvents(type = 'all') {
        const events = this.events[type];
        const dataStr = JSON.stringify(events, null, 2);
        const dataBlob = new Blob([dataStr], { type: 'application/json' });

        const link = document.createElement('a');
        link.href = URL.createObjectURL(dataBlob);
        link.download = `events-${type}-${new Date().toISOString().split('T')[0]}.json`;
        link.click();
    }

    // 限制事件数量
    limitEventsSize(maxSize = 1000) {
        for (const type in this.events) {
            if (this.events[type].length > maxSize) {
                this.events[type] = this.events[type].slice(0, maxSize);
            }
        }
    }


    // 触发自定义事件
    emitEventAdded(event) {
        const customEvent = new CustomEvent('eventAdded', {
            detail: event
        });
        document.dispatchEvent(customEvent);
    }

    // 显示事件详情窗口
    showEventDetail(event) {
        // 移除已存在的详情窗口和提示框
        const existingModal = document.querySelector('.event-detail-modal');
        if (existingModal) {
            existingModal.remove();
        }
        this.hideDataTooltip();

        const modal = document.createElement('div');
        modal.className = 'event-detail-modal';
        modal.innerHTML = `
            <div class="event-detail-content">
                <div class="event-detail-header">
                    <h3>事件详情</h3>
                    <button class="close-btn">&times;</button>
                </div>
                <div class="event-detail-body">
                    <div class="detail-section">
                        <label>类型:</label>
                        <span class="event-type ${event.type}">${this.getTypeText(event.type)}</span>
                    </div>
                    <div class="detail-section">
                        <label>时间:</label>
                        <span>${event.timestamp}</span>
                    </div>
                    <div class="detail-section">
                        <label>消息:</label>
                        <span>${event.message}</span>
                    </div>
                    ${event.previewData && event.previewData !== event.data ? `
                    <div class="detail-section full-width">
                        <label>预览数据:</label>
                        <pre class="event-detail-data preview">${this.formatEventData(event.previewData)}</pre>
                    </div>
                    ` : ''}
                    ${event.data ? `
                    <div class="detail-section full-width">
                        <label>完整数据:</label>
                        <pre class="event-detail-data">${this.formatEventData(event.data)}</pre>
                    </div>
                    ` : ''}
                </div>
            </div>
        `;

        // 关闭按钮事件
        modal.querySelector('.close-btn').addEventListener('click', () => {
            modal.remove();
        });

        // 点击背景关闭
        modal.addEventListener('click', (e) => {
            if (e.target === modal) {
                modal.remove();
            }
        });

        // ESC键关闭
        const escHandler = (e) => {
            if (e.key === 'Escape') {
                modal.remove();
                document.removeEventListener('keydown', escHandler);
            }
        };
        document.addEventListener('keydown', escHandler);

        document.body.appendChild(modal);
    }
}

// 全局实例
window.eventsManager = new EventsManager();